package com.benyi.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; 

public class TcpProxy {
	
	private int port;
	private String remoteIp;
	private int remotePort;
	
	public TcpProxy(int port,String remoteIp,int remotePort){
		this.port=port;
		this.remoteIp=remoteIp;
		this.remotePort=remotePort;
	}
	
	public void start() throws IOException{
		ServerSocket ss=new ServerSocket(port);
		System.out.println("服务已启动,Port:"+port+",代理远程地址:"+remoteIp+",端口:"+remotePort);
		while(true){
			Socket s=ss.accept();
			proxy(s);
		}
	}
	
	private void proxy(Socket from) {
		try{
			System.out.println("代理连接,IP:"+from.getInetAddress());			
			Socket to=new Socket(remoteIp,remotePort);
			doProxy(from,to);
		}catch(Exception e){
			System.out.println("不能连接到目标:"+remoteIp+",Port="+remotePort);
			e.printStackTrace();
		}
	}
	
	private void doProxy(Socket src,Socket to){
		try{
			System.out.println("代理连接,src IP:"+src.getInetAddress()+",to:"+to.getInetAddress());		
			String name=src.getInetAddress().toString()+"->";
			
			InputStream srcIn=src.getInputStream();
			OutputStream srcOut=src.getOutputStream();
			
			InputStream toIn=to.getInputStream();
			OutputStream toOut=to.getOutputStream();
			
			proxyCom(name+"w",srcIn,toOut);
			proxyCom(name+"r",toIn,srcOut);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void proxyCom(String name, InputStream in,OutputStream out){
		ProxyRunner r=new ProxyRunner(name,in,out);
		Thread t=new Thread(r);
		t.start();
	}
	
	private class ProxyRunner implements Runnable{
		String name;
		InputStream in;
		OutputStream out;
		
		public ProxyRunner(String name,InputStream in,OutputStream out){
			this.name=name;
			this.in=in;
			this.out=out;
		}
		
		public void run(){
			System.out.println("开始代理:"+name);
			try{
				int b=in.read();
				while(b!=-1){
					out.write(b);
					b=in.read();
				}
			}catch(Exception e){
				System.out.println("通讯异常:"+name);
				e.printStackTrace();
			}
			try{
				in.close();
			}catch(Exception e){}
			try{
				out.close();
			}catch(Exception e){}
			System.out.println("结束代理:"+name);			
		}
	}
	
	public static void main(String []args) throws Exception {
		System.out.println("参数: 服务端口  目标IP 目标端口");
		if(args.length==0){
			args=new String[3];
			args[0]="3000";
			args[1]="172.16.36.70";
			args[2]="5432";
		}
		int port=Integer.parseInt(args[0]);
		String ip=args[1];
		int to=Integer.parseInt(args[2]);
		
		TcpProxy t=new TcpProxy(port,ip,to);
		t.start(); 		
	}
}
